package cn.benben.auth.service;

import cn.benben.auth.dto.LoginDTO;
import cn.benben.core.constant.CacheConstants;
import cn.benben.core.constant.SecurityConstants;
import cn.benben.core.utils.JwtUtils;
import cn.benben.core.utils.MD5Utils;
import cn.benben.core.utils.StringUtils;
import cn.benben.system.api.SysUserApi;
import cn.benben.system.api.dto.UserResp;
import cn.benben.web.exception.ServiceException;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.benben.redis.service.RedisService;
import com.alibaba.fastjson2.JSONObject;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class LoginService {

    private final static long expireTime = CacheConstants.EXPIRATION;
    private final static String ACCESS_TOKEN = CacheConstants.LOGIN_TOKEN_KEY;

    @Autowired
    private RedisService redisService;

    @DubboReference
    private SysUserApi sysUserApi;

    public Map<String,Object> login(LoginDTO loginDTO){
        Map<String,Object> result = new HashMap<>();

        //TODO 获取人员信息
        JSONObject userInfo = new JSONObject();
        UserResp userResp = sysUserApi.queryUseByUsername(loginDTO.getUsername());

        if (StringUtils.isNull(userResp))
            throw new ServiceException("用户信息不存在");
        if (MD5Utils.MD5matchesPassword(loginDTO.getPassword(),userResp.getSalt(),userResp.getPassWord()))
            throw new ServiceException("账号或密码错误");
        Long userId = userResp.getId();
        String userName = userResp.getUserName();
        userInfo.put("userId",userId);
        userInfo.put("username",userName);

        String token = userId + StrUtil.COLON + IdUtil.fastUUID();
        String userKey = getTokenKey(token);
        redisService.setCacheObject(userKey,userInfo.toJSONString(),expireTime, TimeUnit.MINUTES);

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<>();
        claimsMap.put(SecurityConstants.USER_KEY, userKey);
        claimsMap.put(SecurityConstants.USER_ID, userId);
        claimsMap.put(SecurityConstants.USER_NAME, userName);


        result.put("access_token", JwtUtils.createToken(claimsMap));
        result.put("expires_in",expireTime);
        return result;
    }


    private String getTokenKey(String token) {
        return ACCESS_TOKEN + token;
    }
}
